<?php
session_start();
// include settings and functions
include "../conn/database.php";
include "functions.php";
// if the user submit the form
if(isset($_POST['submit'])) {
	// initialize errors values
	$errors=0;
	$errors_text = '';
	// cleanning the post data from hacking attempt
	$post_data = clean($_POST);
	
	// empty post data verification
	if(empty($_POST['oldcode'])	|| empty($_POST['newcode']) || empty($_POST['con-newcode'])) {
		$errors_text .= "Des champs sont vides<br />";
		$errors++;
	}
	
	// password verification
	if($post_data['newcode'] != $post_data['con-newcode'] 
			|| !check_password($post_data['newcode']) || !check_password($post_data['oldcode'])) {
		$errors_text .= "Les mots de passe ne correspondent pas<br />";
		$errors++;
	}
	
	// if no errors we proceed
	if($errors == 0) {
		// data correction
		$password = MD5($post_data["oldcode"]);
		
		//check the user and password
		$sql = "SELECT * FROM `T_PERSON` WHERE PERSON_SID = '".$_SESSION['guid']."' and PASSWORD = '".$password."' limit 1";
		$res = mysql_query($sql);
		$rows = mysql_num_rows($res);
		$result = mysql_fetch_array($res);
		
		//if user exit and password right
		if($rows>0){
			$newpw = MD5($post_data['newcode']);
			
			$update_sql = "UPDATE `T_PERSON` SET PASSWORD = '".$newpw."'";
			
			if(!mysql_query($update_sql)) {
				$errors_text .= mysql_error()."<br />";
				$errors++;
			}
		} else {
			$errors_text .= "Password not correct.<br />";
			$errors++;
		}
	}
	
	if($errors == 0) {
		$arr['success'] = "1"; 
        $arr['msg'] = 'Change password success!';
	} else {
		$arr['success'] = "0"; 
        $arr['msg'] = $errors_text;
	}
	echo json_encode($arr);
}
?>